import 'package:flustars/flustars.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/pages/home/location/model/monitor_data_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/utils/device_utils.dart';

mixin LocationPageMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {
  MonitorData? monitorData;
  // 手机位置
  BMFCoordinate? phoneLocation;
  // 手机地址信息
  String? phoneAddress;
  // 是否有经纬度
  bool hasLocation = false;

  /// 是否解析过一次地址，假设备解析一次就行了，因为地址都一样
  bool hasReverseGeoCode = false;

  /// 假设备地址
  BMFCoordinate? nineDeviceLocation;
  String? nineDeviceAddress;

  /// 获取假设备定位地址
  /// 仅获取一次，保存在sharePreference中
  Future<void> getNineDeviceAddress() async {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.isNineDevice == false) {
      return;
    }
    var tempNineDeviceAddress = SpUtil.getString('nineDeviceAddress');
    if (hasReverseGeoCode && tempNineDeviceAddress != null && tempNineDeviceAddress.isNotEmpty) {
      nineDeviceAddress = tempNineDeviceAddress;
      return;
    }
    XLogger.info('获取假设备定位地址, latitude: ${phoneLocation?.latitude}, longitude: ${phoneLocation?.longitude}');
    if (phoneLocation == null) {
      Future.delayed(const Duration(seconds: 1), () {
        // 重试
        getNineDeviceAddress();
      });
      return;
    }
    DeviceUtils.reverseGeoCode(latitude: phoneLocation!.latitude, longitude: phoneLocation!.longitude).then((value) {
      hasReverseGeoCode = true;
      nineDeviceAddress = value;
      setState(() {});
      SpUtil.putString('nineDeviceAddress', value);
    });
  }

  /// 根据设备状态获取图标
  String getDeviceIcon(int? deviceStatus) {
    if (deviceStatus == 1) {
      return 'assets/images/map/car_online.png';
    } else if (deviceStatus == 2) {
      return 'assets/images/map/car_offline.png';
    } else if (deviceStatus == 3) {
      return 'assets/images/map/car_sleep.png';
    }
    return 'assets/images/map/car_shutdown.png';
  }
}
